<template>
  <div class="settlement-container">
    <!-- 收货地址 -->
    <div class="address-section">
      <div v-if="selectedAddress" class="selected-address" @click="showAddressSelector = true">
        <div class="address-info">
          <h3>{{ selectedAddress.username }} {{ selectedAddress.phone }}</h3>
          <p>{{ selectedAddress.address }}</p>
        </div>
        <div class="address-arrow">></div>
      </div>
      <div v-else class="add-address" @click="router.push('/address?from=settlement')">  
        <span>+ 添加收货地址</span>
      </div>
    </div>

    <!-- 商品列表 -->
    <div class="order-items">
      <h2>商品信息</h2>
      <div class="items-list">
        <div v-for="item in cartStore.items" :key="item.id" class="item">
          <img :src="`http://localhost:3005/${item.image}`" :alt="item.title">
          <div class="item-info">
            <h3>{{ item.title }}</h3>
            <p class="item-price">¥{{ item.price.toFixed(1) }} × {{ item.quantity }}</p>
          </div>
          <div class="item-total">¥{{ (item.price * item.quantity).toFixed(1) }}</div>
        </div>
      </div>
    </div>

    <!-- 优惠信息 -->
    <div class="discount-section">
      <div class="discount-item">
        <span>优惠券</span>
        <div class="discount-value" @click="showCouponSelector = true">
          <span v-if="selectedCoupon">-¥{{ selectedCoupon.amount }}</span>
          <span v-else>未使用</span>
          <span class="arrow">></span>
        </div>
      </div>
    </div>

    <!-- 支付方式 -->
    <div class="payment-section">
      <h2>支付方式</h2>
      <div class="payment-options">
        <div
          v-for="method in paymentMethods"
          :key="method.id"
          class="payment-option"
          :class="{ active: selectedPayment === method.id }"
          @click="selectedPayment = method.id"
        >
          <img :src="method.icon" :alt="method.name">
          <span>{{ method.name }}</span>
        </div>
      </div>
    </div>

    <!-- 底部结算栏 -->
    <div class="settlement-bar">
      <div class="price-info">
        <span>实付金额：</span>
        <span class="final-price">¥{{ finalAmount.toFixed(1) }}</span>
      </div>
      <button class="submit-btn" @click="submitOrder">提交订单</button>
    </div>

    <!-- 地址选择弹窗 -->
    <div v-if="showAddressSelector" class="modal">
      <div class="modal-content">
        <div class="modal-header">
          <h3>选择收货地址</h3>
          <span class="close-btn" @click="showAddressSelector = false">×</span>
        </div>
        <div class="address-list">
          <div
            v-for="address in addressList"
            :key="address.id"
            class="address-item"
            :class="{ active: selectedAddress?.id === address.id }"
            @click="selectAddress(address)"
          >
            <div class="address-main">
              <h4>{{ address.username }} {{ address.phone }}</h4>
              <p>{{ address.address }}</p>
            </div>
            <div class="address-check" v-if="selectedAddress?.id === address.id">
              ✓
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 优惠券选择弹窗 -->
    <div v-if="showCouponSelector" class="modal">
      <div class="modal-content">
        <!-- 优惠券列表将在这里实现 -->
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useCartStore } from '../../stores/cart'
import { useRouter, useRoute } from 'vue-router'
import axios from 'axios'

const cartStore = useCartStore()
const router = useRouter()
const route = useRoute()

// 地址相关
const showAddressSelector = ref(false)
const selectedAddress = ref(null)
const addressList = ref([])

// 获取地址列表
const fetchAddresses = async () => {
  try {
    const response = await axios.post('http://localhost:3005/address')
    addressList.value = response.data.result
    // 如果有地址，默认选择第一个
    if (addressList.value.length > 0 && !selectedAddress.value) {
      selectedAddress.value = addressList.value[0]
    }
  } catch (error) {
    console.error('获取地址列表失败:', error)
  }
}

// 选择地址
const selectAddress = (address) => {
  selectedAddress.value = address
  showAddressSelector.value = false
}

// 监听路由参数变化
watch(() => route.query.addressId, async (newAddressId) => {
  if (newAddressId) {
    try {
      const response = await axios.post(`http://localhost:3005/address/${newAddressId}`)
      selectedAddress.value = response.data.result
    } catch (error) {
      console.error('获取地址详情失败:', error)
    }
  }
})

// 页面加载时获取地址列表
onMounted(() => {
  fetchAddresses()
  // 如果有地址ID参数，获取对应地址详情
  if (route.query.addressId) {
    const addressId = route.query.addressId
    try {
      axios.post(`http://localhost:3005/address/${addressId}`).then(response => {
        selectedAddress.value = response.data.result
      })
    } catch (error) {
      console.error('获取地址详情失败:', error)
    }
  }

  // 尝试从localStorage恢复未完成的订单数据
  const unfinishedOrder = localStorage.getItem('unfinishedOrder')
  if (unfinishedOrder) {
    const orderData = JSON.parse(unfinishedOrder)
    selectedAddress.value = orderData.address
    selectedPayment.value = orderData.paymentMethod
    selectedCoupon.value = orderData.coupon
  }
})

// 优惠券相关
const showCouponSelector = ref(false)
const selectedCoupon = ref(null)

// 支付方式
const selectedPayment = ref('alipay')
const paymentMethods = [
  { id: 'alipay', name: '支付宝', icon: '/src/assets/R-C.png' },
  { id: 'wechat', name: '微信支付', icon: '/src/assets/wx.jpg' },
  { id: 'card', name: '银行卡', icon: '/src/assets/yxk.jpg' }
]

// 计算最终支付金额
const finalAmount = computed(() => {
  let total = cartStore.totalAmount
  if (selectedCoupon.value) {
    total -= selectedCoupon.value.amount
  }
  return Math.max(total, 0)
})

// 在路由离开前保存未完成的订单数据
const onBeforeRouteLeave = (to, from, next) => {
  // 如果不是去往支付页面，则保存未完成的订单数据
  if (to.path !== '/shopping/payment') {
    const unfinishedOrder = {
      items: cartStore.items,
      address: selectedAddress.value,
      paymentMethod: selectedPayment.value,
      coupon: selectedCoupon.value,
      finalAmount: finalAmount.value,
      timestamp: new Date().toISOString()
    }
    localStorage.setItem('unfinishedOrder', JSON.stringify(unfinishedOrder))
  }
  next()
}

// 提交订单
const submitOrder = async () => {
  try {
    // 数据验证
    if (!cartStore.items.length) {
      alert('购物车为空，请先添加商品')
      return
    }
    if (!selectedAddress.value) {
      alert('请选择收货地址')
      return
    }
    if (!selectedPayment) {
      alert('请选择支付方式')
      return
    }

    // 验证商品数据完整性
    const invalidItems = cartStore.items.filter(item => !item.id || !item.price || item.quantity <= 0)
    if (invalidItems.length > 0) {
      alert('购物车中存在无效商品，请重新添加')
      return
    }

    // 构建订单信息，避免循环引用
    const orderInfo = {
      items: cartStore.items.map(item => ({
        id: item.id,
        title: item.title,
        price: Number(item.price),
        quantity: Number(item.quantity),
        image: item.image
      })),
      address: {
        id: selectedAddress.value.id,
        username: selectedAddress.value.username,
        phone: selectedAddress.value.phone,
        address: selectedAddress.value.address
      },
      paymentMethod: selectedPayment.value,
      finalAmount: Number(finalAmount.value),
      coupon: selectedCoupon.value ? {
        id: selectedCoupon.value.id,
        code: selectedCoupon.value.code,
        amount: Number(selectedCoupon.value.amount)
      } : null,
      orderTime: new Date().toISOString()
    }

    // 模拟订单提交
    await new Promise((resolve, reject) => {
      setTimeout(() => {
        if (Math.random() > 0.1) { // 90%成功率
          resolve()
        } else {
          reject(new Error('网络请求超时'))
        }
      }, 1000)
    })
    
    // 生成订单号
    orderInfo.orderId = `DD${Date.now()}`

    // 保存订单到localStorage
    const storedOrders = localStorage.getItem('orders')
    const orders = storedOrders ? JSON.parse(storedOrders) : []
    orders.unshift(orderInfo) // 将新订单添加到列表开头
    localStorage.setItem('orders', JSON.stringify(orders))
    
    // 清空购物车和未完成订单数据
    cartStore.clearCart()
    localStorage.removeItem('unfinishedOrder')
    
    // 跳转到完成页面并传递订单信息
    router.push({
      path: '/shopping/finish',
      query: {
        orderInfo: JSON.stringify(orderInfo)
      }
    })
  } catch (error) {
    console.error('提交订单失败:', error)
    alert('提交订单失败，请重试')
  }
}
</script>

<style scoped>
.settlement-container {
  width: 400px;
  padding-bottom: 120px;
  background-color: #f8f9fa;
  min-height: fit-content;
  padding-top: 10px;
}

.address-section {
  background: white;
  padding: 15px;
  margin: 0 10px 10px;
  border-radius: 8px;
}

.selected-address {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.address-info h3 {
  margin: 0;
  font-size: 16px;
}

.address-info p {
  margin: 5px 0 0;
  color: #666;
  font-size: 14px;
}

.add-address {
  color: #42b883;
  text-align: center;
  padding: 20px 0;
}

.order-items {
  background: white;
  padding: 15px;
  margin-bottom: 10px;
}

.order-items h2 {
  margin: 0 0 15px;
  font-size: 16px;
}

.item {
  display: flex;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #eee;
}

.item img {
  width: 60px;
  height: 60px;
  object-fit: cover;
  border-radius: 4px;
}

.item-info {
  flex: 1;
  margin: 0 15px;
}

.item-info h3 {
  margin: 0;
  font-size: 14px;
}

.item-price {
  color: #666;
  margin: 5px 0 0;
  font-size: 12px;
}

.item-total {
  color: #f56c6c;
  font-weight: bold;
}

.discount-section {
  background: white;
  padding: 15px;
  margin-bottom: 10px;
}

.discount-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.payment-section {
  background: white;
  padding: 15px;
  margin-bottom: 10px;
}

.payment-options {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.payment-option {
  display: flex;
  align-items: center;
  padding: 10px;
  border: 1px solid #eee;
  border-radius: 4px;
  cursor: pointer;
}

.payment-option.active {
  border-color: #42b883;
  background-color: #f0faf5;
}

.payment-option img {
  width: 24px;
  height: 24px;
  margin-right: 10px;
}

.settlement-bar {
  position: relative;
  background: white;
  padding: 10px 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
  margin-top: 20px;
}

.final-price {
  color: #f56c6c;
  font-size: 20px;
  font-weight: bold;
}

.submit-btn {
  background: #42b883;
  color: white;
  border: none;
  padding: 10px 30px;
  border-radius: 20px;
  font-size: 16px;
  cursor: pointer;
}

.submit-btn:active {
  background: #3aa876;
}

.modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
}

.modal-content {
  background: white;
  width: 90%;
  max-height: 80vh;
  border-radius: 8px;
  padding: 20px;
  overflow-y: auto;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.modal-header h3 {
  margin: 0;
  font-size: 18px;
}

.close-btn {
  font-size: 24px;
  cursor: pointer;
  color: #666;
}

.address-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.address-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border: 1px solid #eee;
  border-radius: 8px;
  cursor: pointer;
}

.address-item.active {
  border-color: #42b883;
  background-color: #f0faf5;
}

.address-main h4 {
  margin: 0;
  font-size: 16px;
}

.address-main p {
  margin: 5px 0 0;
  color: #666;
  font-size: 14px;
}

.address-check {
  color: #42b883;
  font-size: 20px;
}
</style>